package com.situation.config;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.situation.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionContext;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;

@Slf4j
public class MySessionManager extends DefaultWebSessionManager {

    /**
     * 从请求中获取sessionId
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        // 得到请求头的   Authorization
        String token = WebUtils.toHttp(request).getHeader("Authorization");


        if (token == null || token.trim().equals("") || !JWTUtil.parseToken(token)) {
            //按默认规则从cookie取sessionId
//            throw new AuthorizationException();
            return super.getSessionId(request, response);
        } else {
            DecodedJWT decodedJWT = JWTUtil.parseData(token);
            String id = decodedJWT.getId();


            //如果请求头中有 Authorization 则其值为sessionId
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "url");
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return id;
        }
    }

    @Override
    protected void onStart(Session session, SessionContext context) {
        System.out.println("session   start   ...........  ");
        super.onStart(session, context);
        if (!WebUtils.isHttp(context)) {
            log.debug("SessionContext argument is not HTTP compatible or does not have an HTTP request/response pair. No session ID cookie will be set.");
        } else {
            HttpServletRequest request = WebUtils.getHttpRequest(context);
            HttpServletResponse response = WebUtils.getHttpResponse(context);

            //将会话编号保存在resp的header的token中
            Serializable id = session.getId();

            String token = JWTUtil.toToken("xj", "java", id.toString(), null);
            response.setHeader("Authorization", token);

            ConUtil.token = token;
            System.out.println("+++++++++++++++++++++++++++++++++");
            System.out.println(ConUtil.token);
            System.out.println("+++++++++++++++++++++++++++++++++");
            request.removeAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_IS_NEW, Boolean.TRUE);
        }

    }
}
